package nc.ui.yll.pub.report;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.JComponent;

import nc.ui.bd.ref.AbstractRefModel;
import nc.ui.ic.pub.query.SCMTemplateInfo;
import nc.ui.pub.ClientEnvironment;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pub.beans.ValueChangedEvent;
import nc.ui.pub.beans.constenum.DefaultConstEnum;
import nc.ui.pub.beans.constenum.IConstEnum;
import nc.ui.querytemplate.CriteriaChangedEvent;
import nc.ui.querytemplate.ICriteriaChangedListener;
import nc.ui.querytemplate.IQueryTemplateTotalVOProcessor;
import nc.ui.querytemplate.QueryConditionEditor;
import nc.ui.querytemplate.component.UIRefPaneForEnum;
import nc.ui.querytemplate.filter.IFilter;
import nc.ui.querytemplate.filtereditor.DefaultFilterEditor;
import nc.ui.querytemplate.filtereditor.FilterEditorChangedUtil;
import nc.ui.querytemplate.filtereditor.IFilterEditor;
import nc.ui.querytemplate.meta.FilterMeta;
import nc.ui.querytemplate.normalpanel.INormalQueryPanel;
import nc.ui.querytemplate.simpleeditor.SimpleEditor;
import nc.ui.querytemplate.value.DefaultFieldValueElement;
import nc.ui.querytemplate.value.IFieldValueElement;
import nc.ui.querytemplate.value.RefValueObject;
import nc.ui.querytemplate.valueeditor.DefaultFieldValueEditor;
import nc.ui.querytemplate.valueeditor.DefaultFieldValueElementEditor;
import nc.ui.querytemplate.valueeditor.DefaultFieldValueElementEditorFactory;
import nc.ui.querytemplate.valueeditor.IFieldValueElementEditor;
import nc.vo.bd.CorpVO;
import nc.vo.pub.query.QueryConditionVO;
import nc.vo.pub.query.QueryTempletTotalVO;
import nc.vo.querytemplate.TemplateInfo;
import nc.vo.trade.pub.IBillStatus;

// Referenced classes of package nc.ui.fdc.pub:
//            IDlgPowerCtrl

public class FDCDefaultQueryDlg extends JZFDCDefaultQueryDlg {

	public FDCDefaultQueryDlg(java.awt.Container parent,
			INormalQueryPanel normalPnl) {
		super(parent, normalPnl);
		m_itemFilterMap = new HashMap();
		m_fieldValueMap = new HashMap();
		m_fieldFilterMap = new HashMap();
		m_refWhereMap = new HashMap();
		m_modelWhereMap = new HashMap();
		m_filterInfo = (String[][]) null;
		m_fieldRefMap = new HashMap();
		m_fieldDefaultMap = new HashMap();
		m_ceSingleton = null;
		m_digitCurr = null;
		m_digitBase = null;
		adapterInit();
	}

	public FDCDefaultQueryDlg(java.awt.Container parent,
			INormalQueryPanel normalPnl, TemplateInfo ti) {
		super(parent, normalPnl, ti);
		m_itemFilterMap = new HashMap();
		m_fieldValueMap = new HashMap();
		m_fieldFilterMap = new HashMap();
		m_refWhereMap = new HashMap();
		m_modelWhereMap = new HashMap();
		m_filterInfo = (String[][]) null;
		m_fieldRefMap = new HashMap();
		m_fieldDefaultMap = new HashMap();
		m_ceSingleton = null;
		m_digitCurr = null;
		m_digitBase = null;
		adapterInit();
	}

	public FDCDefaultQueryDlg(java.awt.Container parent,
			INormalQueryPanel normalPnl, TemplateInfo ti, String objVal[][]) {
		super(parent, normalPnl, ti);
		m_itemFilterMap = new HashMap();
		m_fieldValueMap = new HashMap();
		m_fieldFilterMap = new HashMap();
		m_refWhereMap = new HashMap();
		m_modelWhereMap = new HashMap();
		m_filterInfo = (String[][]) null;
		m_fieldRefMap = new HashMap();
		m_fieldDefaultMap = new HashMap();
		m_ceSingleton = null;
		m_digitCurr = null;
		m_digitBase = null;
		m_filterInfo = objVal;
		adapterInit();
	}

	public FDCDefaultQueryDlg(java.awt.Container parent,
			INormalQueryPanel normalPnl, TemplateInfo ti, String title) {
		super(parent, normalPnl, ti, title);
		m_itemFilterMap = new HashMap();
		m_fieldValueMap = new HashMap();
		m_fieldFilterMap = new HashMap();
		m_refWhereMap = new HashMap();
		m_modelWhereMap = new HashMap();
		m_filterInfo = (String[][]) null;
		m_fieldRefMap = new HashMap();
		m_fieldDefaultMap = new HashMap();
		m_ceSingleton = null;
		m_digitCurr = null;
		m_digitBase = null;
		adapterInit();
	}

	public FDCDefaultQueryDlg(java.awt.Container parent, TemplateInfo ti) {
		super(parent, ti);
		m_itemFilterMap = new HashMap();
		m_fieldValueMap = new HashMap();
		m_fieldFilterMap = new HashMap();
		m_refWhereMap = new HashMap();
		m_modelWhereMap = new HashMap();
		m_filterInfo = (String[][]) null;
		m_fieldRefMap = new HashMap();
		m_fieldDefaultMap = new HashMap();
		m_ceSingleton = null;
		m_digitCurr = null;
		m_digitBase = null;
		adapterInit();
	}

	protected void adapterInit() {
		initFilterItemInfo();
		registerCriteriaEditorListener(new ICriteriaChangedListener() {

			public void criteriaChanged(CriteriaChangedEvent event) {
				if (event.getEventtype() == 1)
					afterEdit(event, 1);
				if (event.getEventtype() == 4) {
					initFieldRef(event);
					initRefWherePart(event);
				}
				if (event.getEventtype() == 2)
					afterEdit(event, 2);
			}

		});
		registerQueryTemplateTotalVOProceeor(new IQueryTemplateTotalVOProcessor() {

			public void processQueryTempletTotalVO(QueryTempletTotalVO totalVO) {
				if (totalVO != null) {
					QueryConditionVO qryconds[] = totalVO.getConditionVOs();
					initTempletVOs(totalVO, qryconds);
					initFieldDefaultValue(qryconds);
				}
			}

		});
		QueryConditionEditor qe = getQryCondEditor();
		qe.registerFieldValueEelementEditorFactory(new DefaultFieldValueElementEditorFactory(
						qe.getQueryContext()) {

					public IFieldValueElementEditor createFieldValueElementEditor(
							FilterMeta meta) {
						IFieldValueElementEditor editor = initCombox(meta);
						if (editor == null)
							editor = super.createFieldValueElementEditor(meta);
						return editor;
					}

				});
	}

	public void setInitValueRef(String fieldCode, Object editor) {
		m_fieldRefMap.put(fieldCode, editor);
	}

	public void setDefaultValue(String fieldCode, Object value) {
		m_fieldDefaultMap.put(fieldCode, value);
	}

	protected void initFieldRef(CriteriaChangedEvent event) {
		if (m_fieldRefMap.containsKey(event.getFieldCode()))
			setValueRef(event, m_fieldRefMap.get(event.getFieldCode()));
	}

	public CorpVO _getCorp() {
		return getClientEnvironment().getCorporation();
	}

	protected ClientEnvironment getClientEnvironment() {
		if (m_ceSingleton == null)
			m_ceSingleton = ClientEnvironment.getInstance();
		return m_ceSingleton;
	}

	protected String[] getQuantityItems() {
		return null;
	}

	protected String[] getOriginItems() {
		return null;
	}

	protected String[] getBaseItems() {
		return null;
	}

	public DefaultFilterEditor getFilterEditorByCode(String fieldcode) {
		if (!(getQryCondEditor().getCurrentCriteriaEditor() instanceof SimpleEditor))
			return null;
		List filterEditors = ((SimpleEditor) getQryCondEditor()
				.getCurrentCriteriaEditor()).getFilterEditorsByCode(fieldcode);
		if (filterEditors.size() > 0) {
			DefaultFilterEditor dfe = (DefaultFilterEditor) filterEditors
					.get(0);
			return dfe;
		} else {
			return null;
		}
	}

	public DefaultFilterEditor[] getAllFilterEditorByCode(String fieldcode) {
		if (!(getQryCondEditor().getCurrentCriteriaEditor() instanceof SimpleEditor))
			return null;
		List filterEditors = ((SimpleEditor) getQryCondEditor()
				.getCurrentCriteriaEditor()).getFilterEditorsByCode(fieldcode);
		if (filterEditors.size() > 0)
			return (DefaultFilterEditor[]) filterEditors
					.toArray(new DefaultFilterEditor[0]);
		else
			return null;
	}

	protected void initFieldDefaultValue(QueryConditionVO conditions[]) {
		for (int i = 0; i < conditions.length; i++)
			if (m_fieldDefaultMap.containsKey(conditions[i].getFieldCode()))
				conditions[i].setValue(m_fieldDefaultMap.get(
						conditions[i].getFieldCode()).toString());

	}

	private void initFilterItemInfo() {
		String currentFilter[][] = getFilterItemVal();
		if (currentFilter == null || currentFilter.length <= 0
				|| currentFilter[0].length <= 0)
			return;
		String arr$[][] = currentFilter;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			String curVals[] = arr$[i$];
			if (curVals.length < 2 || curVals[0] == null || curVals[1] == null)
				continue;
			String tmpVal[] = curVals[1].split(",");
			m_itemFilterMap.put(curVals[0], tmpVal);
			ArrayList tmpList = new ArrayList();
			for (int i = 0; i < tmpVal.length; i++) {
				m_fieldValueMap.put(tmpVal[i], null);
				if (m_fieldFilterMap.containsKey(tmpVal[i])) {
					((ArrayList) m_fieldFilterMap.get(tmpVal[i]))
							.add(curVals[0]);
				} else {
					tmpList.clear();
					tmpList.add(curVals[0]);
					m_fieldFilterMap.put(tmpVal[i], tmpList);
				}
			}

		}

	}

	protected String[] getRefPKsByFilter(IFilter filter) {
		List valEl = filter.getFieldValue().getFieldValues();
		if (valEl == null)
			return null;
		if (valEl.size() <= 0)
			return null;
		ArrayList retList = new ArrayList();
		DefaultFieldValueElement fieldVals = null;
		for (int i = 0; i < valEl.size(); i++) {
			fieldVals = (DefaultFieldValueElement) valEl.get(i);
			retList.add(((RefValueObject) fieldVals.getValueObject()).getPk());
		}

		return (String[]) retList.toArray(new String[0]);
	}

	protected void afterEdit(CriteriaChangedEvent event, int opInt) {
		if (m_itemFilterMap == null || m_itemFilterMap.size() <= 0)
			return;
		String fieldCode = event.getFieldCode();
		String curFields[] = null;
		if (m_fieldValueMap.containsKey(fieldCode)) {
			String fieldValue[] = null;
			if (opInt == 1)
				fieldValue = getRefPKsByFilter(event.getFilter());
			m_fieldValueMap.put(event.getFieldCode(), fieldValue);
			if (event.getCriteriaEditor() instanceof SimpleEditor) {
				SimpleEditor se = (SimpleEditor) event.getCriteriaEditor();
				curFields = getFilteredFieldCode(fieldCode);
				if (curFields == null || curFields.length == 0)
					return;
				List feList = null;
				DefaultFilterEditor dfe = null;
				String arr[] = curFields;
				int len = arr.length;
				for (int i = 0; i < len; i++) {
					String curField = arr[i];
					feList = se.getFilterEditorsByCode(curField);
					for (Iterator it = feList.iterator(); it.hasNext(); FilterEditorChangedUtil
							.setRefWherePart(dfe, (String) m_refWhereMap
									.get(curField))) {
						IFilterEditor ife = (IFilterEditor) it.next();
						dfe = (DefaultFilterEditor) ife;
						if (!m_modelWhereMap.containsKey(curField)) {
							DefaultFieldValueEditor dfve = (DefaultFieldValueEditor) dfe
									.getFieldValueEditor();
							AbstractRefModel model = ((UIRefPane) dfve
									.getFieldValueElemEditor()
									.getFieldValueElemEditorComponent())
									.getRefModel();
							m_modelWhereMap.put(curField, model.getWherePart());
						}
						String refWhereSql = (String) m_modelWhereMap
								.get(curField);
						if (refWhereSql != null)
							m_refWhereMap.put(curField, (new StringBuilder())
									.append(
											changeWherePart(curField,
													(String[]) m_itemFilterMap
															.get(curField),
													(String) m_refWhereMap
															.get(curField)))
									.append(" and ").append(refWhereSql)
									.toString());
						else
							m_refWhereMap.put(curField, changeWherePart(
									curField, (String[]) m_itemFilterMap
											.get(curField),
									(String) m_refWhereMap.get(curField)));
					}

				}

			}
			List ifList = null;
			String arr$[] = curFields;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i$++) {
				String curField = arr$[i$];
				ifList = event.getCriteriaEditor().getFiltersByFieldCode(
						curField);
				IFilter filter;
				for (Iterator it = ifList.iterator(); it.hasNext(); event
						.getCriteriaEditor().clearData(filter))
					filter = (IFilter) it.next();

			}

		}
	}

	public UIRefPane getUIRefPaneByCode(CriteriaChangedEvent event) {
		DefaultFilterEditor dfe = (DefaultFilterEditor) event.getFiltereditor();
		DefaultFieldValueEditor dfve = (DefaultFieldValueEditor) dfe
				.getFieldValueEditor();
		UIRefPane lur = (UIRefPane) dfve.getFieldValueElemEditor()
				.getFieldValueElemEditorComponent();
		return lur;
	}

	protected void initRefWherePart(CriteriaChangedEvent event) {
		String curFields[] = null;
		curFields = getFilteredFieldCode(event.getFieldCode());
		if (curFields == null || curFields.length == 0)
			return;
		String arr$[] = curFields;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			String curField = arr$[i$];
			if (event.getFieldCode().equals(curField))
				FilterEditorChangedUtil.setRefWherePart(
						(DefaultFilterEditor) event.getFiltereditor(),
						(String) m_refWhereMap.get(curField));
		}

	}

	protected String changeWherePart(String curField, String sourceField[],
			String wherePart) {
		return wherePart;
	}

	private String[] getFilteredFieldCode(String fieldCode) {
		if (!m_fieldFilterMap.containsKey(fieldCode))
			return null;
		ArrayList curFieldList = (ArrayList) m_fieldFilterMap.get(fieldCode);
		ArrayList retList = new ArrayList();
		for (int k = 0; k < curFieldList.size(); k++) {
			String curField = (String) curFieldList.get(k);
			String fields[] = (String[]) m_itemFilterMap.get(curField);
			if (fields == null || fields.length <= 0)
				return null;
			String whereSql = null;
			String arr$[] = fields;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i$++) {
				String tmpField = arr$[i$];
				if (m_fieldValueMap.get(tmpField) == null
						|| ((String[]) m_fieldValueMap.get(tmpField)).length == 0) {
					m_refWhereMap.put(curField, "1=1");
					continue;
				}
				String strValues[] = (String[]) m_fieldValueMap.get(tmpField);
				if (whereSql == null)
					whereSql = (new StringBuilder()).append(tmpField).append(
							" in('").append(strValues[0]).append("'")
							.toString();
				else
					whereSql = (new StringBuilder()).append(whereSql).append(
							" and ").append(tmpField).append(" in('").append(
							strValues[0]).append("'").toString();
				for (int i = 1; i < strValues.length; i++)
					whereSql = (new StringBuilder()).append(whereSql).append(
							",'").append(strValues[i]).append("'").toString();

				whereSql = (new StringBuilder()).append(whereSql).append(") ")
						.toString();
			}

			if (whereSql == null)
				whereSql = " 1=1 ";
			m_refWhereMap.put(curField, whereSql);
			retList.add(curField);
		}

		return (String[]) retList.toArray(new String[0]);
	}

	public String[][] getFilterItemVal() {
		return m_filterInfo;
	}

	protected void initTempletVOs(QueryTempletTotalVO querytemplettotalvo,
			QueryConditionVO aqueryconditionvo[]) {
	}

	protected IFieldValueElementEditor initCombox(FilterMeta meta) {
		if (6 == meta.getDataType()
				&& meta.getFieldCode().endsWith("vbillstatus"))
			return initBillStatus(meta);
		else
			return null;
	}

	protected void setValueRef(CriteriaChangedEvent event, Object refPane) {
		DefaultFilterEditor dfe = (DefaultFilterEditor) event.getFiltereditor();
		if (refPane instanceof UIRefPaneForEnum) {
			UIRefPaneForEnum combIstatus = (UIRefPaneForEnum) getEditorCmpnt(dfe);
			combIstatus.setValues(((UIRefPaneForEnum) refPane).getValues());
		} else if (refPane instanceof UIRefPane)
			setRefModel(dfe, (UIRefPane) refPane);
	}

	protected String getFieldValue(IFilter filter) {
		String fieldValue = null;
		if (filter.getFieldValue() != null
				&& filter.getFieldValue().getFieldValues() != null
				&& filter.getFieldValue().getFieldValues().size() > 0) {
			List fieldValueList = filter.getFieldValue().getFieldValues();
			for (int i = 0; i < fieldValueList.size(); i++) {
				StringBuffer sb = new StringBuffer();
				for (int j = 0; j < fieldValueList.size(); j++) {
					IFieldValueElement fieldValueElement = (IFieldValueElement) fieldValueList
							.get(j);
					Object valueObj = fieldValueElement.getValueObject();
					if (valueObj != null)
						if (valueObj instanceof DefaultConstEnum)
							sb.append(
									((DefaultConstEnum) valueObj).getValue()
											.toString()).append(",");
						else if (valueObj instanceof RefValueObject)
							sb.append(
									((RefValueObject) fieldValueElement
											.getValueObject()).getPk()).append(
									",");
						else
							sb.append(
									fieldValueElement.getValueObject()
											.toString()).append(",");
					fieldValue = sb.substring(0, sb.length() - 1).toString();
				}

			}

		}
		return fieldValue;
	}

	protected String getFieldCode(IFilter filter) {
		return filter.getFilterMeta().getFieldCode();
	}

	protected String getProjectFieldCode() {
		return null;
	}

	protected void setRefModel(DefaultFilterEditor dfe, UIRefPane refPane) {
		UIRefPane lur = (UIRefPane) getEditorCmpnt(dfe);
		lur.setRefModel(refPane.getRefModel());
		UIRefPane rur = (UIRefPane) getRightEditorCmpnt(dfe);
		rur.setRefModel(refPane.getRefModel());
		lur.setNotLeafSelectedEnabled(refPane.isNotLeafSelectedEnabled());
		lur.setReturnCode(refPane.isReturnCode());
		lur.setMultiSelectedEnabled(refPane.isMultiSelectedEnabled());
		lur.setSealedDataButtonShow(refPane.isSealedDataButtonShow());
	}

	protected static JComponent getEditorCmpnt(DefaultFilterEditor dfe) {
		if (dfe == null) {
			return null;
		} else {
			DefaultFieldValueEditor dfve = (DefaultFieldValueEditor) dfe
					.getFieldValueEditor();
			return dfve.getFieldValueElemEditor()
					.getFieldValueElemEditorComponent();
		}
	}

	protected static JComponent[] getEditorCmpntArray(
			DefaultFilterEditor dfeArray[]) {
		if (dfeArray == null)
			return null;
		List list = new ArrayList();
		DefaultFilterEditor arr$[] = dfeArray;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			DefaultFilterEditor def = arr$[i$];
			DefaultFieldValueEditor dfve = (DefaultFieldValueEditor) def
					.getFieldValueEditor();
			JComponent jp = dfve.getFieldValueElemEditor()
					.getFieldValueElemEditorComponent();
			if (jp != null)
				list.add(jp);
		}

		return (JComponent[]) list.toArray(new JComponent[0]);
	}

	protected static JComponent getRightEditorCmpnt(DefaultFilterEditor dfe) {
		if (dfe == null) {
			return null;
		} else {
			DefaultFieldValueEditor dfve = (DefaultFieldValueEditor) dfe
					.getFieldValueEditor();
			return dfve.getRightFieldValueElemEditor()
					.getFieldValueElemEditorComponent();
		}
	}

	public void valueChanged(ValueChangedEvent valuechangedevent) {
	}

	private IFieldValueElementEditor initBillStatus(FilterMeta meta) {
		List enums = null;
		enums = getUsefulBillStatusEnum();
		return new DefaultFieldValueElementEditor(new UIRefPaneForEnum(
				(IConstEnum[]) enums.toArray(new IConstEnum[0])));
	}

	private List getUsefulBillStatusEnum() {
		List enums = new ArrayList();
		for (int i = 0; i < IBillStatusUseful.strStateRemark.length; i++) {
			String billstatusUseful = IBillStatusUseful.strStateRemark[i];
			enums.add(new DefaultConstEnum(Integer
					.valueOf(getBillStatusIndex(billstatusUseful)),
					billstatusUseful));
		}

		return enums;
	}

	private int getBillStatusIndex(String billstatus) {
		int index = -1;
		int i = 0;
		do {
			if (i >= IBillStatus.strStateRemark.length)
				break;
			if (IBillStatus.strStateRemark[i].equals(billstatus)) {
				index = i;
				break;
			}
			i++;
		} while (true);
		return index;
	}

	public HashMap getM_fieldValueMap() {
		return m_fieldValueMap;
	}

	public String[] getPowerCtrlFieldPKs() {
		return null;
	}

	public HashMap getPowerCtrlWherePart(String powerCtrlPKs[],
			StringBuffer wherePart) {
		return null;
	}

	public static Object getValueByFilter(IFilter fil) {
		if (fil.getFieldValue().getFieldValues() != null
				&& fil.getFieldValue().getFieldValues().size() > 0)
			return ((IFieldValueElement) fil.getFieldValue().getFieldValues()
					.get(0)).getValueObject();
		else
			return null;
	}
	private static final long serialVersionUID = 1L;
	private HashMap m_itemFilterMap;
	private HashMap m_fieldValueMap;
	private HashMap m_fieldFilterMap;
	private HashMap m_refWhereMap;
	private HashMap m_modelWhereMap;
	private String m_filterInfo[][];
	private HashMap m_fieldRefMap;
	private HashMap m_fieldDefaultMap;
	private ClientEnvironment m_ceSingleton;
	private String m_digitCurr;
	private String m_digitBase;
}